﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Text.Encodings.Web;

namespace MvcMovie.Controllers
{
    public class HelloWorldController : Controller
    {


        private HttpContext _httpContext;
        private readonly ILogger _logger;
        // 构造函数从ID容器中拿到 (MvcMovieContext)实例
        // 普通类使用这种方式拿到 HttpContext
        public HelloWorldController(IHttpContextAccessor httpContextAccessor, ILogger<HelloWorldController> logger)
        {
            _httpContext = httpContextAccessor.HttpContext;
            _logger = logger;
        }
        // 
        // GET: /HelloWorld/

        public IActionResult Index()
        {
            _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
            var ID = HttpContext.Session.Id;  //Controller可以直接拿到HttpContext
            Console.WriteLine(_httpContext.Request.Host.Value);
            _httpContext.Session.SetString("Name", "Mike");
            _httpContext.Session.SetInt32("Age", 21);

            return View();
        }



        // GET: /HelloWorld/Welcome/ 
        // Requires using System.Text.Encodings.Web;
        //public string Welcome(string name, int numTimes = 1)
        //{
        //    //使用 HtmlEncoder.Default.Encode 防止恶意输入（即 JavaScript）损害应用。
        //    return HtmlEncoder.Default.Encode($"Hello {name}, NumTimes is: {numTimes}");
        //}
        public IActionResult Welcome(string name, int numTimes = 1)
        {
            ViewData["Message"] = "Hello " + name;
            ViewData["NumTimes"] = numTimes;

            return View();
        }
    }
}